﻿using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.Extensions.Logging;
using ZH.GPT.Infrastructures.Configurations;
using ZH.GPT.Infrastructures.Entities;

#nullable disable

namespace ZH.GPT.Infrastructures
{
    /// <summary>
    /// MainDBContext
    /// </summary>
    public partial class MainDBContext : DbContext
    {
        /// <summary>
        /// 记录sql日志
        /// </summary>
        public static readonly ILoggerFactory MyLoggerFactory = LoggerFactory.Create(builder => { builder.AddConsole(); });

        /// <summary>
        /// MainDBContext构造函数
        /// </summary>
        public MainDBContext()
        {
        }

        /// <summary>
        /// MainDBContext构造函数，传入DbContextOptions
        /// </summary>
        /// <param name="options"></param>
        public MainDBContext(DbContextOptions<MainDBContext> options)
            : base(options)
        {
        }

        /// <summary>
        /// 用户信息
        /// </summary>
        public virtual DbSet<User> Users { get; set; }
        /// <summary>
        /// 测试类
        /// </summary>
        public virtual DbSet<Test> TestEntities { get; set; }
        /// <summary>
        /// 消息
        /// </summary>
        public virtual DbSet<ChatMessage> ChatMessage { get; set; }
        /// <summary>
        /// 聊天
        /// </summary>
        public virtual DbSet<Chat> Chat { get; set; }

        /// <summary>
        /// 创建连接
        /// </summary>
        /// <param name="optionsBuilder"></param>
        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            if (!optionsBuilder.IsConfigured)
            {
                optionsBuilder.UseMySql(Conn, ServerVersion.AutoDetect(Conn), b => b.MaxBatchSize(2))
                    .UseLoggerFactory(MyLoggerFactory);
            }
        }

        private string Conn = null;

        /// <summary>
        /// 更换连接，并返回DbContext
        /// </summary>
        /// <param name="conn"></param>
        /// <returns></returns>
        public DbContext ToDbContext(string conn)
        {
            Conn = conn;
            return this;
        }

        /// <summary>
        /// 构造模型
        /// </summary>
        /// <param name="modelBuilder"></param>
        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.HasCharSet("utf8mb4")
                .UseCollation("utf8mb4_0900_ai_ci");
            modelBuilder.ApplyConfiguration(new UserConfiguration());
            modelBuilder.ApplyConfiguration(new ChatConfiguration());
            modelBuilder.ApplyConfiguration(new ChatMessasgeConfiguration());
            modelBuilder.Entity<Test>().Property(t => t.age).HasDefaultValue();
            OnModelCreatingPartial(modelBuilder);
        }

        partial void OnModelCreatingPartial(ModelBuilder modelBuilder);
    }
}
